---@class ComponentPoolMgr
---@field New fun(templateItem:UIComponentInterface):ComponentPoolMgr
ComponentPoolMgr = Class("ComponentPoolMgr")
local t = ComponentPoolMgr
function t:ctor(templateItem)
    self.template = templateItem
    self.unUseList = {}
    self.unUseCount = 0
    self.usedList = {}
end
---@param obj FairyGUI.GComponent [传入obj 获得其绑定的lua table ,如果没有则创建一个新的lua table
---@return table [返回绑定好的lua table
function t:GetBindScript(obj)
    if not obj then return nil end
    local id = obj.id
    local item = self.usedList[id]
    if item then
        return item
    end
    local item = self.unUseList[id]
    if not item then
        if self.template == nil then
            logError("模板为空，无法创建table")
            return nil
        end
        if self.template.New == nil then
            logError("未定义New方法，无法创建table")
            return nil
        end
        item = self.template.New()
        if item.OnCreate then
            item.fguiObj = obj
            item:OnCreate(obj)
        else
            logError("未定义Bind方法，无法绑定obj")
        end
    end
    self.usedList[id] = item
    return item
end
function t:ReturnUsedToPool()
    if self.usedList then
        for k,v in pairs(self.usedList) do
            self.unUseList[k] = v
            self.unUseCount = self.unUseCount + 1
            self.usedList[k] = nil
            if v.OnDisable then
                v:OnDisable()
            end
        end
    end
end
---查找是否有其绑定的lua table
---@param obj FairyGUI.GComponent
function t:FindScript(obj)
    if not obj then return nil end
    local id = obj.id
    local item = self.usedList[id]
    return item
end
---有些界面有定时器的可以手动调用OnEnable 重启定时器等
function t:OnEnable()
    if self.usedList then
        for k,v in pairs(self.usedList) do
            if v.OnEnable then
                v:OnEnable()
            end
        end
    end
end
---有些界面有定时器的可以手动调用OnDisable 关闭定时器等
function t:OnDisable()
    if self.usedList then
        for k,v in pairs(self.usedList) do
            if v.OnDisable then
                v:OnDisable()
            end
        end
    end
end

---界面销毁时调用，释放资源
function t:OnDestroy()
    if self.usedList then
        for k,v in pairs(self.usedList) do
            if v.OnDestroy then
                v:OnDestroy()
            end
            if v.DelReferenceAll then
                v:DelReferenceAll()
            end
        end
    end
    self.template = nil
    self.unUseList = nil
    self.usedList = nil
end
return t